<template>
  <el-dialog
    v-model="visible"
    :title="document?.title"
    width="70%"
    class="document-preview-dialog"
  >
    <div class="document-info" v-if="document">
      <div class="info-item">
        <span class="label">类型：</span>
        <el-tag size="small">{{ document.type }}</el-tag>
      </div>
      <div class="info-item">
        <span class="label">大小：</span>
        <span>{{ formatSize(document.size) }}</span>
      </div>
      <div class="info-item">
        <span class="label">状态：</span>
        <el-tag :type="document.status === 'vectorized' ? 'success' : 'warning'">
          {{ document.status === 'vectorized' ? '已向量化' : '待处理' }}
        </el-tag>
      </div>
      <div class="info-item">
        <span class="label">上传时间：</span>
        <span>{{ formatTime(document.uploadTime) }}</span>
      </div>
    </div>

    <div class="document-content" v-loading="loading">
      <!-- PDF 预览 -->
      <div v-if="isPdf" class="pdf-preview">
        <iframe
          v-if="pdfUrl"
          :src="pdfUrl"
          width="100%"
          height="600"
          frameborder="0"
          type="application/pdf"
          :key="pdfUrl"
        ></iframe>
        <el-empty v-else description="无法预览 PDF 文件" />
      </div>
      
      <!-- HTML 内容预览 -->
      <div v-else-if="isHtml" class="html-content" v-html="content"></div>
      
      <!-- 文本预览 -->
      <div v-else class="content-wrapper">
        <pre v-if="content">{{ content }}</pre>
        <el-empty v-else description="无法预览文件内容" />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button 
          v-if="document?.status === 'pending'"
          type="primary" 
          :loading="vectorizing"
          @click="handleVectorize"
        >
          <template v-if="vectorizing">
            {{ progressMessage || '处理中...' }}
            <template v-if="progress > 0">
              ({{ progress }}%)
            </template>
          </template>
          <template v-else>
            向量化处理
          </template>
        </el-button>
        <el-button @click="visible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { formatTime } from '@/utils/time'
import { formatSize } from '@/utils/file'
import { getDocumentContent, vectorizeDocument } from '@/api/documents'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
  document: {
    type: Object,
    default: () => null
  }
})

const emit = defineEmits(['update:modelValue', 'vectorized'])

const visible = ref(props.modelValue)
const loading = ref(false)
const content = ref('')
const pdfUrl = ref('')
const vectorizing = ref(false)
const progress = ref(0)
const progressMessage = ref('')
const isHtml = ref(false)

// 判断是否为 PDF 文件
const isPdf = computed(() => {
  return props.document?.type?.toLowerCase() === 'pdf'
})

watch(() => props.modelValue, val => {
  visible.value = val
})

watch(visible, val => {
  emit('update:modelValue', val)
  if (val && props.document) {
    loadContent()
  } else {
    content.value = ''
    pdfUrl.value = ''
  }
})

// 生成带时间戳的 URL 以避免缓存问题
const getPdfUrl = (id) => {
  return `/api/documents/${id}/content?raw=true&t=${Date.now()}`
}

async function loadContent() {
  if (!props.document) return
  
  loading.value = true
  try {
    if (isPdf.value) {
      pdfUrl.value = getPdfUrl(props.document.id)
    } else {
      const { data } = await getDocumentContent(props.document.id)
      content.value = data.content
      isHtml.value = data.isHtml
    }
  } catch (error) {
    ElMessage.error('加载文档内容失败')
    console.error('加载文档内容失败:', error)
  } finally {
    loading.value = false
  }
}

async function handleVectorize() {
  if (!props.document) return
  
  vectorizing.value = true
  progress.value = 0
  progressMessage.value = ''

  try {
    await vectorizeDocument(props.document.id, (data) => {
      // 处理进度更新
      if (data.status === 'processing') {
        progress.value = data.progress || 0
        progressMessage.value = data.message || '处理中...'
      }
    })
    
    ElMessage.success('向量化处理成功')
    emit('vectorized', props.document.id)
  } catch (error) {
    ElMessage.error('向量化处理失败: ' + (error.message || '未知错误'))
    console.error('向量化处理失败:', error)
  } finally {
    vectorizing.value = false
  }
}
</script>

<style lang="scss" scoped>
.document-preview-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
  
  .document-info {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      
      .label {
        width: 80px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  
  .document-content {
    min-height: 300px;
    max-height: 600px;
    overflow-y: auto;
    
    .pdf-preview {
      height: 600px;
      width: 100%;
      
      iframe {
        width: 100%;
        height: 100%;
        background-color: #f5f7fa;
        border-radius: var(--el-border-radius-base);
      }
    }
    
    .html-content {
      padding: 20px;
      background-color: var(--el-fill-color-lighter);
      border-radius: var(--el-border-radius-base);
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      line-height: 1.6;
      color: var(--el-text-color-primary);
      
      :deep(h1, h2, h3, h4, h5, h6) {
        margin: 1.5em 0 0.5em;
        font-weight: 600;
        line-height: 1.25;
      }
      
      :deep(h1) { font-size: 2em; }
      :deep(h2) { font-size: 1.5em; }
      :deep(h3) { font-size: 1.25em; }
      :deep(h4) { font-size: 1em; }
      
      :deep(p) {
        margin: 1em 0;
      }
      
      :deep(a) {
        color: var(--el-color-primary);
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
      
      :deep(code) {
        padding: 0.2em 0.4em;
        margin: 0;
        font-size: 85%;
        background-color: var(--el-fill-color);
        border-radius: 3px;
        font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;
      }
      
      :deep(pre) {
        padding: 16px;
        overflow: auto;
        font-size: 85%;
        line-height: 1.45;
        background-color: var(--el-fill-color-dark);
        border-radius: 6px;
        
        code {
          padding: 0;
          margin: 0;
          font-size: 100%;
          background-color: transparent;
          border: 0;
        }
      }
      
      :deep(table) {
        border-collapse: collapse;
        margin: 1em 0;
        width: 100%;
        
        th {
          font-weight: 600;
          background-color: var(--el-fill-color);
        }
        
        td, th {
          border: 1px solid var(--el-border-color);
          padding: 8px 12px;
        }
        
        tr:nth-child(2n) {
          background-color: var(--el-fill-color-light);
        }
      }
      
      :deep(ul, ol) {
        margin: 1em 0;
        padding-left: 2em;
      }
      
      :deep(blockquote) {
        margin: 1em 0;
        padding: 0 1em;
        color: var(--el-text-color-secondary);
        border-left: 0.25em solid var(--el-border-color);
      }
      
      :deep(hr) {
        height: 0.25em;
        margin: 24px 0;
        background-color: var(--el-border-color);
        border: 0;
      }
      
      :deep(img) {
        max-width: 100%;
        height: auto;
        margin: 1em 0;
      }
    }
    
    .content-wrapper {
      padding: 15px;
      background-color: var(--el-fill-color-lighter);
      border-radius: var(--el-border-radius-base);
      
      pre {
        margin: 0;
        white-space: pre-wrap;
        word-break: break-all;
        font-family: monospace;
        line-height: 1.6;
      }
    }
  }
}
</style> 